// Copyright (C) 2024 Kumo inc.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <kthread/internal/thread.h>
#include <turbo/log/logging.h>

namespace kthread {

    Kthread::~Kthread() {
        if(_kid != INVALID_KTHREAD) {
            KLOG(FATAL)<<"you must call `Kthread::join` or `Kthread::detach` before a running kthread ~Kthread() called";
        }
    }
   void Kthread::join(bool crash_if_error) {
        int ec= EINVAL;
        if(_kid != INVALID_KTHREAD) {
            ec = kthread_join(_kid, nullptr);
            if(ec == 0 ) {
                _kid = INVALID_KTHREAD;
            }
        }
        if(ec && crash_if_error ) {
            KLOG(FATAL)<<"Kthread::join failed";
        }
    }

    void Kthread::detach(bool crash_if_error) {
        if(crash_if_error && _kid == INVALID_KTHREAD) {
            KLOG(FATAL)<<"Kthread::detach failed";
        }
        _kid = INVALID_KTHREAD;
    }
}  // namespace kthread
